// 房间流水查看页面
const app = getApp()

Page({
  data: {
    roomInfo: null,
    records: [],
    loading: false,
    hasRecords: false
  },

  onLoad(options) {
    // 从参数或缓存获取房间信息
    const roomId = options.room_id
    if (roomId) {
      this.setData({ roomInfo: { id: roomId } })
      this.getRoomRecords()
    } else {
      this.checkRoomFromCache()
    }
  },

  onShow() {
    // 每次显示时重新检查
    if (this.data.roomInfo) {
      this.getRoomRecords()
    }
  },

  // 从缓存检查房间信息
  checkRoomFromCache() {
    const RoomCache = require('../../utils/roomCache')
    const roomData = RoomCache.getRoomBasicInfo()

    if (!roomData) {
      wx.showModal({
        title: '无法查看流水',
        content: '请先加入房间',
        showCancel: false,
        confirmText: '确定',
        success: () => {
          wx.navigateBack({
            delta: 1
          })
        }
      })
      return
    }

    this.setData({
      roomInfo: roomData
    })
    this.getRoomRecords()
  },

  // 获取房间流水数据
  getRoomRecords() {
    if (!this.data.roomInfo) {
      return
    }

    this.setData({ loading: true })

    wx.request({
      url: `${app.globalData.baseUrl}/api/accounting/room-records`,
      method: 'GET',
      data: {
        room_id: this.data.roomInfo.id
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            records: res.data.data,
            hasRecords: res.data.data.length > 0
          })
        } else {
          wx.showModal({
            title: '获取流水失败',
            content: res.data.message || '获取房间流水数据失败',
            showCancel: false,
            confirmText: '确定',
            success: () => {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        }
      },
      fail: (err) => {
        console.error('获取房间流水失败:', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
      }
    })
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  },

  // 分享给好友
  async onShareAppMessage() {
    return {
      title: '房间流水详情',
      path: `/pages/room-records/room-records?room_id=${this.data.roomInfo.id}`,
      imageUrl: '/images/share-room.jpg'
    }
  }
})
